package com.miukoo.aikao.ucenter.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miukoo.aikao.core.dtos.PageReqDto;
import com.miukoo.aikao.core.dtos.PageResDto;
import com.miukoo.aikao.ucenter.api.v1.AchievementApi;
import com.miukoo.aikao.ucenter.dto.request.AchievementReqDto;
import com.miukoo.aikao.ucenter.dto.response.AchievementRespDto;
import com.miukoo.aikao.ucenter.mapper.AchievementMapper;
import com.miukoo.aikao.ucenter.pojos.Achievement;
import com.miukoo.aikao.ucenter.services.AchievementService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 用户考试成绩查询、插入管理
　* @Author miukoo<miukoo@126.com>
　* @Date 2020/11/19 19:14
　* @Version 1.0
  */
@Service
public class AchievementServiceImpl extends ServiceImpl<AchievementMapper, Achievement> implements AchievementService, AchievementApi {

    @Override
    public PageResDto<List<AchievementRespDto>> listForUserId(PageReqDto<AchievementReqDto> reqDto, Long userId) {

        AchievementReqDto params = reqDto.getParams();

        if(params==null){
            params = new AchievementReqDto();
        }
        params.setUserId(userId);

        //转换结果
        IPage<AchievementRespDto> pageData = baseMapper.paging(reqDto.toPage(), params);
        return PageResDto.result(pageData.getTotal(),pageData.getRecords());
    }

    @Override
    public void joinResult(Long userId,String userName,String paperTitle, Long examId, Short score, boolean passed) {

        //查询条件
        QueryWrapper<Achievement> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Achievement::getUserId, userId) .eq(Achievement::getExamId, examId);

        Achievement record = this.getOne(wrapper, false);
        if(record == null){
            record = new Achievement();
            record.setCreateTime(new Date());
            record.setUpdateTime(new Date());
            record.setUserId(userId);
            record.setExamId(examId);
            record.setMaxScore(score);
            record.setExamTitle(paperTitle);
            record.setRealName(userName);
            record.setPassed(passed);
            this.save(record);
            return;
        }

        // 修复低分数不加入统计问题
        record.setTryCount((short)(record.getTryCount()+1));
        record.setUpdateTime(new Date());

        if(record.getMaxScore() < score){
            record.setMaxScore(score);
            record.setPassed(passed);
        }

        this.updateById(record);

    }
}
